
package com.wu.demo.farmework.interceptor;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wu.demo.common.HttpStatus;
import com.wu.demo.common.annotation.IgnoreAuth;
import com.wu.demo.common.domain.LoginUser;
import com.wu.demo.common.exception.CustomException;
import com.wu.demo.farmework.manager.TokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthTokenInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuthTokenInterceptor.class);
    @Autowired
    private TokenManager tokenManager;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        Boolean methodAnnotation;
        Boolean classAnnotation;
        if (handler instanceof HandlerMethod) {
            methodAnnotation = ((HandlerMethod) handler).hasMethodAnnotation(IgnoreAuth.class);
            classAnnotation = ((HandlerMethod) handler).getMethod().getDeclaringClass().isAnnotationPresent(IgnoreAuth.class);
        } else {
            return true;
        }

        //如果有@IgnoreAuth注解，则不验证token
        if (methodAnnotation  || classAnnotation ) {
            return true;
        }
        //从header中获取token
        LoginUser loginUser = tokenManager.getLoginUser(request);
        if (ObjectUtils.isNotNull(loginUser)) {
            tokenManager.refreshToken(loginUser);//刷新token

        } else {
            logger.error("token失效" + request.getRequestURI() + ":" + tokenManager.getToken(request));
            throw new CustomException("token失效", HttpStatus.UNAUTHORIZED);
        }
        return true;
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }
}

